package com.gitee.huxing.course.conc.conc01.op;

/**
 * @Description:
 * @ProjectName: JavaCourse
 * @Package: com.gitee.huxing.course.conc.cono01.op
 * @ClassName: WaitAndNotify
 * @Author: huxing
 * @DateTime: 2021-08-20 上午10:50
 */
public class WaitAndNotify {

    public static void main(String[] args) {
        MethodClass methodClass = new MethodClass();
        // 创建生产者线程
        Thread thread1 = new Thread(() -> {
            try {
                methodClass.product();
            } catch (InterruptedException ex){
                ex.printStackTrace();
            }
        }, "thread1");
        // 创建消费者线程
        Thread thread2 = new Thread(() -> {
            try {
                methodClass.consumer();
            } catch (InterruptedException ex){
                ex.printStackTrace();
            }
        }, "thread2");

        thread1.start();
        thread2.start();
    }
}

class MethodClass{
    /** 定义最大生产量 **/
    private final int MAX_COUNT = 20;

    int productCount = 0;

    public synchronized void product() throws InterruptedException{
        while (true){
            System.out.println(Thread.currentThread().getName() + ":::run:::" + productCount);
            Thread.sleep(10L);
            if (productCount > MAX_COUNT){
                System.out.println("货舱已经满，不必生产了");
                wait();
                System.out.println("product wait");
            } else {
                productCount++;
            }
            notifyAll();
            System.out.println("product notify all");
        }
    }

    public synchronized void consumer() throws InterruptedException{
        while (true){
            System.out.println(Thread.currentThread().getName() + ":::run:::" + productCount);
            Thread.sleep(10L);
            if (productCount <= 0){
                System.out.println("货舱已经没货了，无法消费");
                wait();
                System.out.println("consumer wait");
            } else {
                productCount--;
            }
            notifyAll();
            System.out.println("consumer notifyAll");
        }
    }
}
